import requests
from datetime import datetime
from SqlalchemyConfig import SessionLocal
from models.DeviceInfo import DeviceInfo
import logging
import configparser
import os
from RedisClient import RedisClient

logger = logging.getLogger(__name__)

# 初始化 Redis 客户端
redis_client = RedisClient()

def read_base_url(config_file='config.ini'):
    """从配置文件中读取基础 URL 和 API 路径"""
    config = configparser.ConfigParser()
    if not os.path.exists(config_file):
        logger.error(f"❌ 配置文件 {config_file} 不存在")
        return None

    try:
        config.read(config_file, encoding='utf-8')

        base_url = config.get('BaseApi', 'base_url', fallback=None)
        api_path = '/api/v1/resource/page'

        if not base_url:
            logger.error("❌ 配置文件中未找到 base_url")
            return None

        full_url = f"{base_url.rstrip('/')}/{api_path.lstrip('/')}"
        return full_url

    except Exception as e:
        logger.error(f"❌ 读取配置失败：{str(e)}", exc_info=True)
        return None


def sync_device_region_info():
    """
    同步设备 regionId 到 dr_device_info_list 表中
    """

    # 从 Redis 获取 Token
    auth_token = redis_client.get_token()
    if not auth_token:
        logger.critical("🛑 Redis 中未找到认证 Token，无法执行接口请求")
        return False

    # 从配置文件读取 base URL
    base_url = read_base_url()
    if not base_url:
        logger.error("❌ 获取接口地址失败，终止同步。")
        return False

    payload = {
        "register": True,
        "limit": 9999,
        "page": 1,
        "status": 1
    }

    headers = {
        "Authorization": auth_token
    }

    db = SessionLocal()
    try:
        logger.info(f"📡 正在请求设备数据接口：{base_url}")
        response = requests.post(base_url, json=payload, headers=headers, timeout=10)

        if response.status_code != 200:
            logger.warning(f"⚠️ 请求失败，状态码：{response.status_code}")
            return False

        data = response.json()
        content_list = data.get('content', {}).get('content', [])

        if not content_list:
            logger.info("ℹ️ 接口返回内容为空。")
            return False

        for item in content_list:
            region_id = item.get('regionId')
            if not region_id or len(region_id) < 6:
                logger.warning(f"⚠️ regionId 不合法: {region_id}")
                continue

            area_id = region_id[:6]

            existing = db.query(DeviceInfo).filter(DeviceInfo.region_id == region_id).first()

            if existing:
                pass  # 可选更新 update_time
            else:
                new_record = DeviceInfo(
                    region_id=region_id,
                    area_id=area_id,
                    create_time=datetime.now(),
                    update_time=datetime.now()
                )
                db.add(new_record)
                db.commit()
                logger.info(f"✅ [{region_id}] 已成功插入数据库！")

        return True

    except Exception as e:
        db.rollback()
        logger.error(f"❌ 数据同步出错：{str(e)}", exc_info=True)
        return False
    finally:
        db.close()